package com.songxh.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.songxh.common.BaseContext;
import com.songxh.common.R;
import com.songxh.pojo.User;
import com.songxh.service.UserService;
import com.songxh.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author songxh
 * @create 2022-04-26-19:46
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    /**
     * 发送手机短信验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpServletRequest request){
        String phone = user.getPhone();
        if (!StringUtils.isEmpty(phone)){
            //生成一个4为的验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //用阿里云短信服务来发送短信

            log.info("==========》手机验证码为："+code);
            //存到session当中
            request.getSession().setAttribute(phone,code);

            return R.success("手机短信验证码发送成功");
        }
        return R.error("短信发送失败");
    }


    /**
     * 登录业务
     * @param
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpServletRequest request){

        //获取电话和验证码
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");

        //获取session中的验证码并进行比对
        String sessCode = (String) request.getSession().getAttribute(phone);
        if (sessCode!=null && sessCode.equals(code)){
            //判断是否为新用户
            QueryWrapper<User> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            User user = userService.getOne(queryWrapper);
            if (user==null){
                //是新用户
                user=new User();
                user.setPhone(phone);
                userService.save(user);
            }
            request.getSession().setAttribute("user",user.getId());
            return R.success(user);
        }

        return R.error("登录失败");
    }


    //user/loginout
    @PostMapping("/loginout")
    private R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }

}
